import React, {
  useEffect,
  useImperativeHandle,
  useRef,
  forwardRef
} from 'react'
import styled from 'styled-components'
import style from '../../assets/global-style'
import { prefixStyle } from '../../api/utils'

const Container = styled.div`
  .icon_wrapper {
    position: fixed;
    z-index: 1000;
    margin-top: --10px;
    margin-left: --10px;
    color: ${style['theme-color']};
    font-size: 14px;
    display: none;
    transition: transform 1s cubic-bezier(0.62, -0.1, 0.86, 0.57);
    transform: translate3d(0, 0, 0);
    > div {
      transition: transform 1s;
    }
  }
`

const MusicNote = forwardRef((props, ref) => {
  const iconRef = useRef()
  const ICON_NUMBER = 3
  const transform = prefixStyle('transform')

  console.log(transform)
  const createNode = txt => {
    const template = `<div class='icon_wrapper'>${txt}</div>`
    const tmpNode = document.createElement('div')

    tmpNode.innerHTML = template
    return tmpNode.firstChild
  }

  const startAnimation = ({ x, y }) => {
    for (let i = 0; i < ICON_NUMBER; i++) {
      let domArr = [].slice.call(iconRef.current.children)
      let item = domArr[i]

      if (item.running === false) {
        item.style.left = x + 'px'
        item.style.top = y + 'px'
        item.style.display = 'inline-block'
        setTimeout(() => {
          item.running = true
          item.style[transform] = `translate3d(0, 750px, 0)`
          const icon = item.querySelector('div')

          icon.style[transform] = `translate3d(-40px, 0, 0)`
        }, 20)
        break
      }
    }
  }

  useImperativeHandle(ref, () => ({
    startAnimation
  }))

  useEffect(() => {
    for (let i = 0; i < ICON_NUMBER; i++) {
      let node = createNode(`<div class="iconfont">&#xe642;</div>`)

      iconRef.current.appendChild(node)
      let domArr = [].slice.call(iconRef.current.children)

      domArr.forEach(item => {
        item.running = false
        item.addEventListener(
          'translate3d',
          () => {
            this.style['display'] = 'none'
            this.style[transform] = 'translate3d(0, 0, 0)'
            this.running = false

            let icon = this.querySelector('div')

            icon.style[transform] = `translate3d(0, 0, 0)`
          },
          false
        )
      })
    }
  }, [])

  return <Container ref={iconRef}></Container>
})

export default React.memo(MusicNote)
